using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Mmht.DB
{
    public class PageDB
    {
        public bool CreateOrUpdatePage(string type, string title, string content, int created_by)
        {
            DateTime now = DateTime.Now;
            string sql = string.Empty;
            if (!SelPictures_type(type))
            {
                string sqlConst = @"insert into page(type,page_title,page_content,created_by,created_at)values('{0}','{1}','{2}','{3}','{4}')";
                sql = string.Format(sqlConst, type, title, content, created_by.ToString(), now);
            }
            else
            {
                string sqlConst = @"update page set page_title='{0}',page_content='{1}',created_by='{2}',created_at='{3}' where type='{4}'";
                sql = string.Format(sqlConst, title, content, created_by.ToString(), now, type);
            }
            operate op = new operate();
            bool bl = op.Execute(sql);
            return bl;
        }

        public bool UpdatePictures(string type,string pictures)
        {
            if (SelPictures_type(type))
            {
                string sql = string.Empty;
                sql = @"update page set pictures='" + pictures + "' where type='" + type + "'";
                operate op = new operate();
                bool bl = op.Execute(sql);
                return bl;
            }
            else return false;
        }

        public bool UpdateFiles(string type,string files)
        {
            if (SelPictures_type(type))
            {
                string sql = string.Empty;
                sql = @"update page set files='" + files + "' where type='" + type + "'";
                operate op = new operate();
                bool bl = op.Execute(sql);
                return bl;
            }
            else return false;
        }

        public DataRow GetPageRow(string type)
        {
            string sql = string.Empty;
            sql = "select * from page where type='"+type+"' order by created_at desc";
            DataTable dt = new DataTable();
            operate op = new operate();
            dt = op.Query(sql);
            if (dt != null && dt.Rows.Count>0)
            {
                return dt.Rows[0];
            }
            else return null;
        }

        private bool SelPictures_type(string type)
        {
            string sql = string.Empty;
            sql = @"select * from page where type='" + type + "'";
            operate op = new operate();
            DataTable dt = op.Query(sql);
            bool bl = false;
            if (dt != null && dt.Rows.Count > 0)
            {
                bl = true;
            }
            return bl;
        }

    }
}
